import datetime
import time

from iwencai import SearchWenCai
from database import DataBase


def init_table():
    db = DataBase("data.db")
    db.execute('''create table if not exists lgt_100
                      --'陆股通持股前100'
    (
        name  text not null, -- '股票名称'
        code varchar(6) not null, -- '股票代码'
        weight int,-- '当天的顺序'
        price decimal(10,2) not null ,-- '现价'
        percent decimal(10,2) not null ,-- '持股比例'
        total text not null, -- '持股量'
        day text not null, -- '哪一天的数据'
        update_time datetime, -- '创建时间'
        primary key(code,name,day)
    ) 
    ''')
    db.close()


if __name__ == "__main__":
    init_table()
    test = SearchWenCai(False)

    database = DataBase("data.db")
    curdate = datetime.date.today()
    curdate = curdate- datetime.timedelta(days=1)

    startdate = datetime.date(curdate.year-1, 12, 31)
    date = database.query("select max(day) from lgt_100", {})
    if len(date) > 0:
        startdate = datetime.datetime.strptime(date[0][0], '%Y-%m-%d').date()

    while startdate < curdate:
        if curdate.isoweekday() == 6 or curdate.isoweekday() == 7:
            print(curdate, end=' ')
            print('今天是周末')
        else:
            starttime = time.time()
            search_value = "{}月{}日 陆股通持股比例前100 收盘价".format(curdate.month, curdate.day)
            print(search_value)
            try:
                data = test.search(search_value)
            except:
                print("{} 搜索异常".format(search_value))
                continue

            endtime = time.time()
            print("搜索解析花费时间：{}".format(endtime - starttime))
            sqls = []
            for v in data:
                # 返回结果 weight code name percent price total
                sql = '''insert or ignore into lgt_100(name,code,weight,price,percent,total,day,update_time)
                         values('{}','{}',{},{},{},'{}','{}',{})'''\
                    .format(v[2], v[1], v[0], v[4].replace(',', ''), v[3], v[5], curdate.isoformat(), 'CURRENT_TIMESTAMP'
                )
                sqls.append(sql)
            database.batch_execute(sqls)
            print("插入数据库耗时 {}".format(time.time() - endtime))
            # time.sleep(random.randint(1, 5))
        curdate -= datetime.timedelta(days=1)

    test.close()  # 关闭浏览器
    database.close()  # 关闭数据库
